
// base
import React, { PureComponent, createRef } from 'react'
import DocumentTitle from 'react-document-title'
// import BetterScroll from 'components/betterScroll'

// network
import { getGoodsDetail, createPurchaseOrder, updateOrderAddress } from '@api/home'
import { handelCollect } from '@api'
import { store } from '@store'
import { fetchAddressAction, selectedAddressAction, updateOrder } from '@store/actionCreators'



// componets
import { Button, Toast } from 'antd-mobile'
import { GoodsDetailStyle, CartOptionStyle } from '../style'
import { MySwiper, DeliveryInfo, StatusTimer, GoodsDetailInfo, PingTuan } from '../component/goodsDetail'

const _Toast = Toast


class GoodsDetail extends PureComponent {

  uniacid = store.getState().appConfig.uniacid
  isApplet = store.getState().appConfig.isApplet
  gdBt = createRef()

  state = {
    goodsDetail: {},
    haveContent: false,
    timerObj: {},
    localCollect: false,
    goodsNum: 1,
    goodsOption: '',
    activeKey: [],
    optionDetail: {}, // 规格价格数量相关
    cartType: [
      { value: '常规车', key: 'cgc001' },
      { value: '冷链车', key: 'llc002' },
    ],
    cartLength: [
      { value: '9.6米', key: 'len001' },
      { value: '6.8米', key: 'len002' },
      { value: '4.2米', key: 'len003' }
    ],
    packTypeIndex: -1,
    cartTypeIndex: 0,
    cartLengthIndex: 0,
  }


  goodsDetailConfig = {
    id: this.props.match.params.id,
    uniacid: this.uniacid
  }

  async componentDidMount() {

    localStorage.removeItem('fullLoad') // 确保进去submit 前 不存在旧的 缓存

    store.dispatch( updateOrder({
      orderno: null,
      acceptableTime: null,
      loadage: null,
      remark: "",
      isRead: false,
      agree: false
    }) ) // 发起拼单前保证 缓存是空的

    let res = await getGoodsDetail(this.goodsDetailConfig);

    this.setState({
      goodsDetail: res.data,
      localCollect: res?.data?.collect,
      goodsNum: 1,
      guige: res.data?.guige
    }, () => {
      try {

        // console.log( this.gdBt.current?.BScroll?.refresh() )
        // this.gdBt.current.BScroll.refresh();
      } catch (error) {
        console.log(error)
      }
    })
  }

  render() {

    console.log('render渲染')

    const { goodsDetail, activeKey, goodsNum, localCollect, guige, cartType, cartLength, cartLengthIndex, cartTypeIndex } = this.state;
    
    const { good, img, sendout_address, gdesc, id, goods_myparam, goods_param, goods_services, group } = this.state.goodsDetail;
    let res = 'https://res.lexiangpingou.cn/images/826/2020/';
    const collect = localCollect ? `${res}10/PGzWu2w8RvAQbruagZRTUrtU8z8iQG.png` : `${res}09/P29Z6W2g6B6mGn9Uzc6g48n9BEGcGA.png`;

    return (
      <>
        <GoodsDetailStyle>
          <DocumentTitle title={this.props.route.title} />

          {goodsDetail.id && <div className="main">

            {img?.length > 0 && <MySwiper data={img} time={3000} />}

            <StatusTimer {...good} />

            <div className="content">
              <div className="goods-title">
                <div className="title-text">
                  {
                    good.name
                  }
                </div>
                <div className="title-option flex-row">
                  <div className="goods-favorites flex-row" onClick={e => { this.addCollect(id) }}>
                    <img src={collect} alt="" />
                    <span style={localCollect ? { color: '#ff762e' } : {}}>收藏</span>
                  </div>
                  <div className="goods-share flex-row" onClick={e => { this.props.history.push('/goodsdetailshare/' + id) }}>
                    <img src="https://res.lexiangpingou.cn/images/826/2020/09/fAxizXu96s0u6J9TupZSixsXMUG7Wg.png" alt="" />
                    <span>分享</span>
                  </div>
                </div>
              </div>


              <div className="cart-option goods-detail-box">
                <CartOptionStyle>
                  <div className="cart-option flex-column" style={{ textAlign: 'center', border: 'none' }}>
                    <div className="option-items" >
                      <p className="option-text">车辆属性</p>
                      <ul className=" flex-row">
                        {
                          cartType.map((val, key) => {
                            return (
                              <li key={key + val.key} onClick={e => { this.setState({ cartTypeIndex: key }) }} className={key === cartTypeIndex ? 'active' : ''}>{val.value}</li>
                            )
                          })
                        }
                      </ul>
                      <ul className=" flex-row">
                        {
                          cartLength.map((val, kex) => {
                            return (
                              <li key={kex + val.key} onClick={e => { this.setState({ cartLengthIndex: kex }) }} className={kex === cartLengthIndex ? 'active' : ''}>{val.value}</li>
                            )
                          })
                        }

                      </ul>
                    </div>
                  </div>
                </CartOptionStyle>
              </div>

              {
                guige &&
                <div className="goods-option ">
                  {
                    guige &&
                    guige.map((itex, kex) => {
                      return (
                        <div key={kex + itex.name} className="option-items" >
                          <p className="option-text">{itex.name}</p>
                          <ul className=" flex-row">
                            {
                              itex.option.map((itey, key) => {
                                return (
                                  <li key={key + itey} onClick={e => { this.saveOption(kex, key) }} className={key === activeKey[kex] ? 'active' : ''}>{itey}</li>
                                )
                              })
                            }
                          </ul>
                        </div>
                      )
                    })
                  }
                </div>
              }

              {this.filterExpiredGroup(group).length > 0 && <PingTuan groupList={this.filterExpiredGroup(group)} gid={id} />}

              <DeliveryInfo gid={id} address={sendout_address} goodsServices={goods_services} freightTable={good.freight_forecast} cartTable={good.car_type} refreshHeight={e => { this.refreshHeight() }} />

              <GoodsDetailInfo gdesc={gdesc} defaultSX={goods_param} mySX={goods_myparam} refreshHeight={e => { this.refreshHeight() }} />

              {/* <div className="yunfeishouming common-card">
                  <img src="https://res.lexiangpingou.cn/images/826/2020/10/ht6u2W3TW6u8TO0luwzCNTwGTwT0cW.png" alt="" />
                </div> */}

            </div>


            <div className="goods-submit flex-row global-bottom-fixed">
              <div className="left flex-row" >
                <div className="reduce" onClick={e => { this.changeGoodsNum('reduce') }}>-</div>
                <div className="line"></div>
                <input className="goods-num" type="number" enterkeyhint="done" value={goodsNum} name="goodsNum" onChange={e => { this.handelInput(e) }} />
                <div className="line" ></div>
                <div className="plus" onClick={e => { this.changeGoodsNum('plus') }}>+</div>
              </div>

              <Button className="submit-button" onClick={e => { this.orderSubmit(id) }}> 发起拼单 </Button>

            </div>

          </div>}

        </GoodsDetailStyle>
      </>
    );
  }


  filterExpiredGroup(groupList) {
    // 过滤过期的团
    let now = parseInt(new Date().getTime().toString().slice(0, -3))
    return groupList.filter((item) => {
      return parseInt(item.endtime) > now
    })
  }


  refreshHeight() {
    console.log('刷新高度')
    // this.gdBt.current.BScroll.refresh();
  }

  saveOption(x, y) {
    const { activeKey } = this.state
    let temp = []
    temp = activeKey
    temp[x] = y
    let str = ''

    this.state.goodsDetail.guige.map((item, key) => (
      item.option.map((optionItem, optionIndex) => (
        (activeKey[key] === optionIndex) && (str += optionItem + '+')
      )
      )
    ))

    str = str.substr(0, str.length - 1)
    this.setState({
      activeKey: temp,
      goodsOption: str
    }, () => {
      if (activeKey.length === this.state.goodsDetail.guige.length) {
        this.updateOptionNum(str)
      }
    })
  }

  async updateOptionNum(specs) {
    console.log(this.getGoodsDetail)
    // 更新规格数量
    this.goodsDetailConfig.specs = specs
    let res = await getGoodsDetail(this.goodsDetailConfig)
    if (res.status === 200) {
      this.setState({
        goodsDetail: res.data
      })
    } else {
      console.log(res.msg)
    }

  }


  changeGoodsNum(type) {
    if (type === 'reduce') {
      if (this.state.goodsNum <= 1) {
        Toast.info('不能再减啦', 1)
      } else {
        this.setState({
          goodsNum: parseInt(this.state.goodsNum) - 1
        })
      }
    } else {
      this.setState({
        goodsNum: parseInt(this.state.goodsNum) + 1
      })
    }
  }

  orderSubmit(id) {
    // 提交订单
    const { goodsNum, goodsOption, addressId, activeKey, cartLength, cartType, cartLengthIndex, cartTypeIndex } = this.state
    const { guige, good } = this.state.goodsDetail
    const { isApplet } = store.getState().appConfig
    const { packaging_attributes, price_validity } = good
    const { defaultAddress } = store.getState()

    let nowTime = new Date().getTime().toString().slice(0, -3)

    store.dispatch(fetchAddressAction) // 下单本地缓存更新为默认地址

    let [cartTypes, cartSize, packType] = ["", "", ""]

    if (packaging_attributes) {
      packType = packaging_attributes[activeKey[0]]
    }
    cartSize = cartLength[cartLengthIndex].value
    cartTypes = cartType[cartTypeIndex].value


    if (!cartTypes || !cartSize) {
      Toast.info('请选择完整的车辆属性', 1)
      return false
    }

    let getCarNum = {
      uniacid: this.uniacid,
      id: id,
      cartType: cartTypes, // 车辆类型
      cartSize, // 车辆长度
      packType: packType, // 包装类型
    }

    let updateOrderAddressConfig = {
      deposit_orderno: '',
      province: defaultAddress.proc,
      city: defaultAddress.cityc,
      county: defaultAddress.countyc,
      detailed_address: defaultAddress.detailed_address
    }


    let createOrder = {
      uniacid: this.uniacid,
      id: id,
      specs: goodsOption, //商品规格
      addressid: addressId, // 有默认地址给默认地址，没有就在下一页去选择
      min_num: goodsNum,
      buy: 1, // 传 1 表示购买
      tuan_id: 0,
      cartType: cartTypes, // 车辆类型
      cartSize, // 车辆长度
      packType: packType, // 包装类型
    }

    if (parseInt(price_validity) < parseInt(nowTime)) {
      _Toast.info('该商品供应价已过期')
      return
    } else {

      createPurchaseOrder(getCarNum).then(res => {
        if (res.status === 200) { // 接口响应正确
          if (res.data.carnum) { // 确保选择的 规格 在后台已设置装载量
            console.log('装载量', res.data.carnum)
            if (parseInt(goodsNum) > parseInt(res.data.carnum)) { // 购买数量大于 该组合规格装载量
              Toast.info('购买数量超过承载量', 1)
            } else {
              if (parseInt(goodsNum) === parseInt(res.data.carnum)) {  // 购买数量等于 该组合规格装载量
                console.log('刚好满载')
                localStorage.setItem('fullLoad', 1)
              }else{
                localStorage.removeItem('fullLoad')
              }
              if (!guige || guige.length === 0) { // 该商品无规格
                if (parseInt(goodsNum) > good.stock) { // 购买数量超过现有库存
                  Toast.info('购买数量超过现有库存', 1)
                } else {
                  createPurchaseOrder(createOrder).then(res => {
                    if (res.status === 200) {
                      updateOrderAddressConfig.deposit_orderno = res.data
                      updateOrderAddress(updateOrderAddressConfig).then(rex => {
                        store.dispatch(selectedAddressAction({})) // 清除 选择地址
                        isApplet ? window.navigateToWebWiew('/submit/' + res.data + '/' + 0) : this.props.history.push('/submit/' + res.data + '/' + 0)
                      })
                    } else {
                      Toast.fail(res.msg)
                    }
                  })

                }
              } else {
                if (activeKey.length === guige.length) {
                  console.log('允许')
                  if (parseInt(goodsNum) > good.stock) {
                    Toast.info('购买数量超过现有库存', 1)
                  } else {
                    createPurchaseOrder(createOrder).then(res => {
                      if (res.status === 200) {
                        updateOrderAddressConfig.deposit_orderno = res.data
                        updateOrderAddress(updateOrderAddressConfig).then(rex => {
                          store.dispatch(selectedAddressAction({})) // 清除 选择地址
                          isApplet ? window.navigateToWebWiew('/submit/' + res.data + '/' + 0) : this.props.history.push('/submit/' + res.data + '/' + 0)
                        })
                      } else {
                        Toast.fail(res.msg)
                      }
                    })
                  }
                } else {
                  Toast.info('请先选择商品规格', 1)
                }
              }
            }
          } else {
            Toast.info('该组合未设置装载量', 1)
          }
        } else {
          Toast.info(res.msg, 1)
        }
      })
    }




  }
  handelInput = e => {
    this.setState({
      [e.target.name]: e.target.value.replace(/[^\d]/g, '')
    })
  }

  addCollect(id) {
    handelCollect({
      goodsid: id,
      uniacid: this.uniacid
    }).then(res => {
      if (res.status === 200) {
        Toast.success(res.msg, 1)
        this.setState({
          localCollect: !this.state.localCollect
        })
      } else {
        Toast.fail(res.msg, 1)
      }
    })
  }





}

export default GoodsDetail;